<template>
	<view class="roll-wrap" v-if="list">
		<view class="roll-main" :class="{runing: !isReset}" :style="{width: rollMainWidth + 'px', 'transform' : `translateX(${moveX}px)`, '--duration': duration +'s', '--diffW':  diffW}">
			<text class="text-item" :style="{...customStyle}" v-for="(text, index) in list" :key="index">{{text}}</text>
		</view>
	</view>
</template>
<script>
	import { toRaw } from 'vue';
import { selector, selectorAll } from '@/uni_modules/hbxw-utils/js_sdk/hbxw-utils.js'
	export default {
		props: {
			// loop: {
			// 	type: Boolean,
			// 	default: true
			// },
			list: {
				type: Array,
				default() {
					return null;
				}
			},
			duration: {
				type: Number,
				default: 5
			},
			customStyle: {
				type: Object,
				default() {
					return {}
				}
			}
		},
		data() {
			return {
				rollWrapWidth: 0,
				rollMainWidth: 0,
				moveX: 0,
				diffW: 0,
				isReset: false
			}
		},
		mounted() {
			if (this.list && this.list.length > 0) {
				this.init();
			}
		},
		watch: {
			list(newVal) {
				if (newVal && newVal.length > 0) {
					this.init();
				}
			}
		},
		methods: {
			updateList(list){
				console.log(toRaw(list),'toRaw(list)')
				return toRaw(list)
			},
			async init() {
				const rollWrapRes = await selector('.roll-wrap', this);
				const textItemRes = await selectorAll('.text-item', this);
				let rollMainWidth = 0
				textItemRes.forEach((textItem) => rollMainWidth += textItem.width);
				this.rollMainWidth = rollMainWidth;
				this.rollWrapWidth = rollWrapRes.width;
				this.diffW = this.rollMainWidth - rollWrapRes.width;
				if (this.rollMainWidth <= this.rollWrapWidth) {
					return;
				}
				this.play();
				
				// console.log('rollWrapRes:textItemRes: ', rollWrapRes, textItemRes, this.diffW);
			},
			play() {
				this.isReset = false;
				this.moveX = -this.rollMainWidth;
				setTimeout(() => {
					this.isReset = true;
					this.moveX = this.rollWrapWidth;
					this.$emit('end');
					setTimeout(() => {
						this.play();
					}, 100);
				}, this.duration * 1000)
			}
		}
	}
</script>
<style lang="scss" scoped>
	.roll-wrap {
		width: 100%;
		height: 100%;
		overflow: hidden;
	}
	.roll-main{
		height: 100%;
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
		font-size: 28rpx;
		color: #333;
		&.runing{
			transition: transform var(--duration) linear;
		}
		.text-item{
			flex:none;
			margin-right: 20rpx;
		}
	}
</style>
